from datetime import datetime

from app_api.models import Log, LogType
import re
from utils.ip_get_addr import seperate_ip


def login_log_save(request, user, login_type):
    # if re.match('1[3-9][0-9]{9}$', request.data["username"]):
    #     text = '手机号登录'
    #     code = 1
    # else:
    #     text = "用户名登录"
    #     code = 0
    login_type = LogType.objects.get(code=login_type)
    # TODO 获取动态城市
    if "Mozilla" in request.META['HTTP_USER_AGENT']:
        dec = "web"
    else:
        dec = "未知设备"
    cip = request.META['REMOTE_ADDR']

    addr = seperate_ip(cip)
    if not addr:
        addr = seperate_ip("139.227.248.190")

    log = Log(userid=user.id, time=datetime.now(), ip=cip, device=dec, city=addr,
              type=login_type)
    log.save()
